#include "controller.h"


Controller::Controller()
{
    combs = (Resender *)malloc(sizeof(Resender));
    nCombs = 0;
    nKeys = 0;
    state = (bool *)malloc(255 * sizeof(bool));
//    pressed = 0;
}

int Controller::findComb(Key comb)
{
    if (!nCombs)
        return -1;
    int l = 0, r = nCombs + 1;

    while(l + 1 < r)
    {
        if (combs[(l + r) / 2].getComb().getCombination() > comb.getCombination())
            r = (l + r) / 2;
        else
            l = (l + r) / 2;
    }

    if (combs[l].getComb() == comb)
        return l;
    else
        return -l - 1;
}

void Controller::bindComb(Key newComb, void (*newFunc)())
{
    tmp = findComb(newComb);
    if (tmp >= 0)
    {
        combs[tmp].rebind(newFunc);
    }
    else
    {
        tmp = -tmp - 1;
        combs = (Resender *)realloc(combs, sizeof(Resender) * ++nCombs);
        for (int j = nCombs - 1; j > tmp; --j)
            combs[j] = combs[j - 1];
        combs[tmp].rebind(newFunc);
    }
}



void Controller::keyPress(char key)
{
    Key k(key);
    cur += k;
    tmp = findComb(cur);
    if (tmp >= 0)
        combs[tmp].call();
}

void Controller::keyRelise(char key)
{
    Key k(key);
    cur -= Key(k);
    tmp = findComb(cur);
    if (tmp >= 0)
        combs[tmp].call();
}

bool Controller::keyIsPressed(Key key)
{
//    for (tmp = 0; tmp < 8; tmp++)
//        if (key.)
}
